package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Dish;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.DishMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.ShoppingCartService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired
    ShoppingCartMapper shoppingCartMapper;
    @Autowired
    DishMapper dishMapper;
//    @Autowired
//    SetmealMapper setmealMapper;
    /**
     * 添加购物车
     * @param shoppingCartDTO
     */
    @Override
    public void add(ShoppingCartDTO shoppingCartDTO) {
        //1.根据用户id和参数查询 当前用户之前有没有把对应商品加入购物车
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDTO,shoppingCart);
        shoppingCart.setUserId(userId);
        ShoppingCart shoppingCartDB = shoppingCartMapper.findShoppingCartByOptions(shoppingCart);

        if(shoppingCartDB != null){
            //2.用户之前添加过数据,数量+1,修改
            shoppingCartDB.setNumber(shoppingCartDB.getNumber() + 1);
            shoppingCartMapper.updateNumberById(shoppingCartDB);
        }else{
            Long dishId = shoppingCartDTO.getDishId();
            //3.第一次添加 => shoppingCart对象
            if(dishId != null){
                //3.1 添加菜品
                //根据菜品id查询菜品
                Dish dish = dishMapper.findById(dishId);
                shoppingCart.setName(dish.getName());
                shoppingCart.setImage(dish.getImage());
                shoppingCart.setAmount(dish.getPrice());
            }else{
                //3.2 添加套餐
                //todo 这个代码我不写了
                //根据套餐id查询套餐
                //shoppingCart.setName();
                //shoppingCart.setImage();
                //shoppingCart.setAmount();
            }
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());

            //存入数据库
            shoppingCartMapper.save(shoppingCart);
        }
    }

    @Override
    public List<ShoppingCart> list() {
        //1.获取用户id
        //2.根据用户id查询购物车表
        return shoppingCartMapper.findByUserId(BaseContext.getCurrentId());
    }
}
